﻿using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Share
{
    //一个UDP数据发送类，
    public class UDPSender : SingletonObject<UDPSender>
    {
        string m_strUrl;
        private const int DEFAULT_PORT = 8080; // 统一使用8080端口
        protected override void OnInit()
        {
            m_strUrl = "127.0.0.1"; // 默认发送到本地
        }

        public bool SendData(string data, string ip = "127.0.0.1", int port = 8080, Encoding encoding = null)
        {
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    return false;
                }

                encoding = encoding ?? Encoding.UTF8;

                using (UdpClient client = new UdpClient())
                {
                    client.Client.SendTimeout = 3000;
                    client.Client.ReceiveTimeout = 3000;

                    byte[] bytes = encoding.GetBytes(data);
                    int sent = client.Send(bytes, bytes.Length, ip, port);
                    return sent == bytes.Length;
                }
            }
            catch (SocketException sex)
            {
                return false;
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError($"[UDPSender] Error: {ex.Message}");
                return false;
            }
        }

        // 保持原有方法兼容性
        public void SendData(string data)
        {
            SendData(data, m_strUrl, DEFAULT_PORT);
        }

        private string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return string.Empty;
        }
    }
}
